<?php
/**
 * Author:xsc
 * Time:2023/10/19 14:54
 */

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Repository\MemberRepo;
use App\Extensions\Coupon\CouponService;
use App\Repository\SpecialPrivilegeUgcOrderRepo;

class UgcAutoReceiveJob extends Job
{

    use  InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务可尝试的次数
     * @var int
     */
    public $tries = 3;

    /**
     * 任务失败前允许的最大异常数
     * @var int
     */
    public $maxExceptions = 3;

    /**
     * 在超时之前任务可以运行的秒数
     * @var int
     */
    public $timeout = 30;

    private $id;

    public function __construct(int $id)
    {
        $this->id = $id;
    }

    public function handle()
    {
        $id = $this->id;
        $order_info = SpecialPrivilegeUgcOrderRepo::getInstance()->getById($id);

        $order_sn = $order_info['ordersn'];

        Log::info('[ugc自动领取]订单号:' . $order_sn);

        if ($order_info['status'] != 1) {
            Log::info('[ugc自动领取]订单号:' . $order_sn . '状态异常');
            return false;
        }

        // 截止时间
        if (strtotime($order_info['end_time']) < time()) {
            Log::info('[ugc自动领取]订单号:' . $order_sn . '已过期');
            return false;
        }

        $type = $order_info['type'];
        $to_member_id = $order_info['to_member_id'];
        $to_member = MemberRepo::getInstance()->getInfoById($to_member_id);
        $to_mobile = $to_member['mobile'];

        // 卡券
        $coupon = CouponService::getInstance();

        try {

            if ($type == 1) {
                // 1.转移卡券
                $res = $coupon->changeMsgCode($order_info['coupon_code'], $order_info['woff_code'], $order_info['ordersn'], $to_mobile);
                if ($res) {
                    //更新订单
                    $data = [
                        'status'       => 2,
                        'woff_code'    => $res['newMsgCode'],
                        'receive_time' => date('Y-m-d H:i:s'),
                        'coupon_no'    => $res['newOrderSubNo'],
                    ];
                    SpecialPrivilegeUgcOrderRepo::getInstance()->save($data, $order_info['id']);
                } else {
                    throw new \Exception('卡券转移失败' . $order_sn);
                }
            } else if ($type == 2) {
                // 2.发放红包
                $params = [
                    'sku_code'      => $order_info['coupon_code'],
                    'coupon_num'    => 1,
                    'notice_url'    => env('APP_URL') . '/api/openapi/v1/callback/ugcAutoReceiveCallback',
                    'phone'         => $to_mobile,
                    'third_no'      => $order_info['ordersn'],
                    'collection_no' => $order_info['goods_id'],
                ];
                $res = $coupon->buySku($params);
                if ($res) {
                    //更新订单
                    $data = [
                        //'status'    => 3,
                        'coupon_no' => $res[0]['orderSubNo'],
                    ];
                    SpecialPrivilegeUgcOrderRepo::getInstance()->save($data, $order_info['id']);
                } else {
                    throw new \Exception('发放红包失败' . $order_sn);
                }
            }
        } catch (\Exception $e) {
            Log::info('[ugc自动领取]失败:' . $e->getMessage());

            // 5s之后再次加入队列
            $this->release(5);

            // 抛出异常会直接重新加入队列
            //throw $e;
        }
    }

}
